from common.tidtool import *
from common.adbtool import *
from common.packageparse import get_apk_lautc, get_apkname
from multiprocessing import Pool
import unittest, random
from common.appiumserveruntil import start, stop_server
from case.logintestcase import testCase
from common.config import apk_path, test_phone_type
from common.iosadbtool import getplatfoemversion as getiosplatform
from common.parmer import Parmer


def runnerCaseApp(devices):
    '''利用unittest的testsuite来组织测试用例'''
    test_suit = unittest.TestSuite()
    test_suit.addTest(Parmer.parametrize(testcase_klass=testCase, parame=devices))  # 扩展的其他的测试用例均这样添加
    unittest.TextTestRunner(verbosity=2).run(test_suit)


def getdevicespol(devicests: list) -> list:
    devices_Pool = []
    if test_phone_type == "Android":
        for i in range(0, len(devicests)):
            pool = []
            initApp = {}
            device = devicests[i]
            apkname = get_apkname(apk_path)
            desired_caps = {
                'platformName': 'Android',
                'deviceName': device['devices'],  # adb  deivces
                'platformVersion': getPlatForm(devicests[i]['devices']),  # 从设置中可以获取
                'appPackage': apkname,  # 包名
                'udid': devicests[i]['devices'],
                'appActivity': get_apk_lautc(apk_path),  # apk的launcherActivity
                # 'skipServerInstallation': True
            }
            initApp['deviceName'] = device['devices']
            initApp["port"] = device["port"]
            initApp['appPackage'] = apkname
            initApp['desired_caps'] = desired_caps
            pool.append(initApp)
            devices_Pool.append(initApp)
    elif test_phone_type == "IOS":
        for i in range(0, len(devicests)):
            pool = []
            initApp = {}
            device = devicests[i]
            desired_caps = {
                'platformName': 'IOS',
                'deviceName': device['devices'],  # adb  deivces
                'platformVersion': getiosplatform(devicests[i]['devices']),  # 从设置中可以获取
                'appPackage': "待做",  # 包名
                'udid': devicests[i]['devices'],
                'appActivity': "待做",  # apk的launcherActivity
                # 'skipServerInstallation': True
            }
            initApp['deviceName'] = device['devices']
            initApp["port"] = device["port"]
            initApp['appPackage'] = "待做"
            initApp['desired_caps'] = desired_caps
            pool.append(initApp)
            devices_Pool.append(initApp)
    return devices_Pool


def runnerPool(getDevices):
    '''
       根据链接的设备生成不同的dict
       然后放到设备的list里面
       设备list的长度产生进程池大小
    '''

    devices_Pool = getdevicespol(getDevices)
    pool = Pool(len(devices_Pool))
    pool.map_async(runnerCaseApp, devices_Pool)
    pool.close()
    pool.join()


def run():
    if test_phone_type == "Android":
        devices = get_devices()
    elif test_phone_type == "IOS":
        devices = getdevicespol()
    else:
        devices = []
    port_list = []
    if len(devices) > 0:
        for dev in devices:
            app = {}
            app["devices"] = dev
            port = str(random.randint(5641, 5646))
            app["port"] = port
            port_list.append(port)
            devices.append(app)
        start(port_list)
        runnerPool(devices)
        try:
            stop_server(port_list)
        except Exception as e:
            print("关闭服务失败，原因：%s" % e)
    else:
        print('请链接测试设备')


if __name__ == "__main__":
    # parames = {"port": 4723}
    # suite = un.TestSuite()
    # suite.addTests(Parmer.parametrize(testCase, parames))
    # rune = un.TextTestRunner()
    # rune.run(suite)
    run()
